package com.example.netty.handler;

import com.alibaba.fastjson.JSON;
import com.example.netty.common.Message;
import com.example.netty.constant.ReqMessageType;
import com.example.netty.service.GameService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zclever <304078606@qq.com>
 * @date 2021-03-03
 */
@Component
@ChannelHandler.Sharable
public class GameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(GameHandler.class);

    @Autowired
    private GameService gameService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        Message req = JSON.parseObject(msg.text(), Message.class);
        if(req.getType()== ReqMessageType.inGame){
            logger.info("用户进入游戏:{}", req.getContent());

            Message res = gameService.inGame(ctx.channel(),req.getContent());
            ctx.channel().writeAndFlush(res.toMsg());
        }else if(req.getType()== ReqMessageType.outGame){
            logger.info("用户退出游戏:{}", req.getContent());

            Message res = gameService.outGame(ctx.channel());
            ctx.channel().writeAndFlush(res.toMsg());
        }else{
            msg.retain();
            ctx.fireChannelRead(msg);
        }
    }

}
